<template>
  <div class="params">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card组件 -->
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 商品分类选择区 -->
      <el-row>
        <el-col :span="24">
          <span>选择商品分类：</span>
          <!-- 选择商品的级联选择框 -->
          <el-cascader
            :props="cascaderProp"
            expand-trigger="hover"
            :options="cateList"
            v-model="selectedCateList"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab栏 -->
      <!-- {{activeName}} -->
      <el-tabs v-model="activeName" @tab-click="tabClicked">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isdisabled"
            @click="adddialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <!-- 渲染标签tag start-->
                <el-tag
                  :key="index"
                  v-for="(tag, index) in scoped.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scoped.row, index)"
                  >{{ tag }}</el-tag
                >
                <!-- 渲染标签tag end-->
                <!-- 编辑标签 start -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
                <!-- 编辑标签 end -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(scoped.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scoped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isdisabled"
            @click="adddialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <!-- 渲染标签tag start-->
                <el-tag
                  :key="index"
                  v-for="(tag, index) in scoped.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scoped.row, index)"
                  >{{ tag }}</el-tag
                >
                <!-- 渲染标签tag end-->
                <!-- 编辑标签 start -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
                <!-- 编辑标签 end -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(scoped.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scoped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数和静态属性对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addruleForm"
        :rules="addrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeName == 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数和静态属性对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editruleForm"
        :rules="editrules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeName == 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="editruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类商品列表
      cateList: [],
      // 通过级联选择框选中的所有分类的id数组
      selectedCateList: [],
      // 指定分类级联选择框中数据的对应关系
      cascaderProp: {
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      // 设置tab栏中默认被选中的页签
      activeName: "many",
      // 动态数据列表
      manyTableDate: [],
      // 静态数据列表
      onlyTableDate: [],
      // 添加动态参数和静态属性对话框
      adddialogVisible: false,
      // 添加的表单数据
      addruleForm: {
        attr_name: ""
      },
      // 添加的校验规则
      addrules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      },
      // 修改动态参数和静态属性对话框
      editdialogVisible: false,
      // 修改的表单数据
      editruleForm: {
        attr_name: ""
      },
      // 修改的校验规则
      editrules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      }
      // // 控制tag中input和按钮的显示和隐藏
      // inputVisible: false,
      // // 标签input的双向绑定
      // inputValue: ""
    };
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      // 调用api接口 获取到所有的商品分类，总共为三级分类
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 }
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      // 把获取到的数据给cateList
      this.cateList = res.data;
    },
    // 只要级联选择框中的内容发生了变化 都会触发change事件
    handleChange() {
      if (this.selectedCateList.length !== 3) {
        // 如果选中的不是三级分类，就强制清空数组
        this.selectedCateList = [];
        this.manyTableDate = [];
        this.onlyTableDate = [];
      } else {
        // 否则 就是选中了三级分类
        this.getTableDate();
      }
    },
    // 根据选中的商品类型获取表格数据
    async getTableDate() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("分类数据获取失败");

      // 遍历属性参数 展开行的数据
      res.data.forEach(item => {
        // console.log(item);
        // 先把字符串切割成数组
        let arr = item.attr_vals.split(" ");
        // console.log(arr)
        // 然后再让attr_vals以数组的形式存在
        item.attr_vals = arr;
        // 控制tag中input和按钮的显示和隐藏
        item.inputVisible = false;
        // 标签input的双向绑定
        item.inputValue = "";
      });
      // console.log(res)

      //   判断当前展示的页签是否为动态参数
      if (this.activeName == "many") {
        // 为动态参数赋值
        this.manyTableDate = res.data;
      } else {
        // 为静态属性赋值
        this.onlyTableDate = res.data;
      }
    },
    // 标签页被点击了
    tabClicked() {
      if (!this.cateId) return;
      this.getTableDate();
    },
    // 添加对话框 重置表单
    addDialogClosed() {
      // 清空表单
      this.$refs.addFormRef.resetFields();
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false;
        // 发起post请求 添加新参数
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addruleForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加参数失败");
        // 重新获取表格数据
        this.getTableDate();
        // 弹框关闭
        this.adddialogVisible = false;
      });
    },
    // 修改 回显
    async editParams(row) {
      // 打开弹框
      this.editdialogVisible = true;
      // 发起ajax请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取信息失败");
      // 把获取到的数据给表单 回显
      this.editruleForm = res.data;
    },
    // 点击确定 修改内容
    editParamsList() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editruleForm.attr_id}`,
          {
            attr_name: this.editruleForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) return this.$message.error("更新信息失败");
        this.$message.success("更新信息成功");
        // 关闭弹框
        this.editdialogVisible = false;
        // 刷新页面
        this.getTableDate();
      });
    },
    // 修改对话框 重置表单
    editDialogClosed() {
      // 清空表单
      this.$refs.editFormRef.resetFields();
    },
    // 删除
    removeParams(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http
            .delete(`categories/${this.cateId}/attributes/${id}`)
            .then(() => {
              this.getTableDate();
            });
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 点击确定按钮（回车）的时候 失去焦点的时候
    async handleInputConfirm(row) {
      // input隐藏
      row.inputVisible = false;
      // 如果值为空 就return
      if (!row.inputValue.trim()) {
        row.inputVisible = false;
        row.inputValue = "";
        return false;
      }
      // 判断this.inputvalue值的length是不是大于0 如果大于0 把该值通过push方法添加到数组中
      // 去掉两边的空格 如果剩下的长度大于0
      if (row.inputValue.trim().length > 0) {
        // 就把输入的值添加到数组的最后
        row.attr_vals.push(row.inputValue.trim());
      }
      // 清空
      row.inputValue = "";
      // 发起ajax请求
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("添加标签失败");
    },
    // 点击按钮（+new tag）
    showInput(row) {
      // 让input显示
      row.inputVisible = true;
      // 刚显示的时候自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
        console.log(_);
      });
    },
    // 删除标签
    async handleClose(row, index) {
      // 删除索引 删除一个
      row.attr_vals.splice(index, 1);
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("添加标签失败");
    }
  },
  created() {
    this.getCateList();
  },
  // 计算属性
  computed: {
    // 计算属性在定义的时候一定要定义为方法 但是在页面上使用的时候直接当作属性来用，而且，在计算属性中，必须return一个计算的结果
    isdisabled: function() {
      // 如果级联选择框中的值的长度等于3，按钮不禁用
      if (this.selectedCateList.length == 3) return false;
      //   否则 禁用
      return true;
    },
    // 当前选中的三级分类的id
    cateId: function() {
      // 如果选中了三级分类 则值位为数字，如果没有选中三级分类，值为null
      if (this.selectedCateList.length == 3) return this.selectedCateList[2];
      return null;
    }
  }
};
</script>

<style>
.el-alert {
  margin-bottom: 15px;
}
.el-card,
.el-table {
  margin-top: 10px;
}
.el-tag {
  margin-right: 5px;
}
.input-new-tag {
  width: 90px;
  margin: 10px 0px;
}
</style>
